package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.ContentTemplVersion;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.entity.PatientTaskContent;
import com.bbcare.followup.plat.entity.PtContent;
import com.bbcare.followup.plat.entity.QuestionData;
import com.bbcare.followup.plat.service.IAppPatientAotuService;
import com.bbcare.followup.plat.store.ibatis.IBsEnegryInfoDAO;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import com.bbcare.followup.plat.store.ibatis.IPtContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPtContentHisDAO;
import com.bbcare.followup.plat.store.ibatis.IQuestionsDataDAO;

/**
 * @name: app孕妇自主饮食运动，血糖监控计划实现类
 * @author: wuyz
 * @createTime: 2017.5.31
 * @description: app孕妇自主饮食运动，血糖监控计划
 * @modify:
 *
 */
@Service
public class AppPatientAotuService implements IAppPatientAotuService {
	private final Log logger = LogFactory.getLog(AppPatientAotuService.class);

	@Autowired
	private IPatientDAO patientDao;
	@Autowired
	private IPatientQueueSchemeDAO patientQueueSchemeDao;
	@Autowired
	private IPatientTaskContentDAO patientTaskConDao;
	@Autowired
	private IQuestionsDataDAO IQuestionsDataDAO;
	@Autowired
	private IPtContentDAO IPtContentDAO;
	@Autowired
	private IPtContentHisDAO IPtContentHisDAO;
	@Autowired
	private IContentTemplDAO contentTemplDao;
	@Autowired
	private IBsEnegryInfoDAO IBsEnegryInfoDAO;
	@Autowired
	private IFollowQueueDAO queueDao;

	@Autowired
	private IPatientTaskDAO patientTaskDao;

	// 查询用户当前问卷模板和填写过的问卷等信息
	@Override
	public Map<String, Object> PatientFollowInit(Map<String, Object> paramMap) throws Exception {
		logger.info("PatientFollowInit 入参" + paramMap.toString());
		Map<String, Object> Map = new HashMap<String, Object>();
		// 通过服务号码和用户姓名查询userid
		paramMap.put("tenantId", "0");
		List<Patient> Patient = patientDao.selectByPhoneNo(paramMap);
		String userId = "";// 用户id
		String queueId = "";// 队列id
		String type = "1";
		String opType = "Y";
		String followDeptId = "";// 科室id
		if (Patient.size() > 0) {
			userId = Patient.get(0).getId();
			// 查询患者当前队列
			HashMap<String, Object> qryPqsMap = new HashMap<String, Object>();
			qryPqsMap.put("userId", userId);
			List<String> statulist = new ArrayList<String>();// 查询出暂停和正常 两个状态
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT); // 待审核状态
			qryPqsMap.put("status", statulist);
			List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(qryPqsMap);
			if (pqsList.size() > 0 && null != pqsList) {
				queueId = pqsList.get(0).getQueueId();
				HashMap<String, Object> retOutMap = new HashMap<String, Object>();
				Map<String, Object> userMapIn = new HashMap<String, Object>();
				userMapIn.put("userId", userId);
				Patient ptVo = patientDao.selectById(userMapIn);
				if (null == ptVo || "".equals(ptVo.getId())) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
				}
				PatientQueueScheme psVo = pqsList.get(0);
				String userStatus = psVo.getUserStatus();
				if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
					throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL,
							"患者在该队列中状态异常，无法进行相关操作！");
				}

				String taskId = "";
				HashMap<String, Object> taskInMap = new HashMap<String, Object>();
				taskInMap.put("ptSchemeId", psVo.getId());
				taskInMap.put("endTime", DateUtil.getCurrDate());
				taskInMap.put("beginTime", DateUtil.getCurrDate());
				taskInMap.put("taskType",Constants.TASK_TYPE_NONSCHEME_REALTIME);
				taskInMap.put("revSeqNo", 0);// 去掉建档任务
				List<PatientTask> ptVoList = patientTaskDao.select(taskInMap);
				if (CollectionUtils.isEmpty(ptVoList)) {
					// if (!StringUtils.isEmpty(custValType)) {
					// 若没有当前窗口期的任务，则用第一次随访任务替代(针对安医大项目)
					taskInMap.clear();
					taskInMap.put("ptSchemeId", psVo.getId());
					taskInMap.put("seqNo", 1);
					taskInMap.put("taskType",Constants.TASK_TYPE_NONSCHEME_REALTIME);
					ptVoList = patientTaskDao.select(taskInMap);
					if (CollectionUtils.isEmpty(ptVoList)) {
						// throw new
						// AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TASK_NOT_EXIST,
						// "该患者无任务信息！");
						return retOutMap;
					}
					/*
					 * } else { return retOutMap; }
					 */
				}
				PatientTask ptTaskVo = ptVoList.get(0);
				taskId = ptTaskVo.getId();

				taskInMap.clear();
				taskInMap.put("taskId", taskId);
				taskInMap.put("contTemplType", type);// 问卷模板类型
				taskInMap.put("userId", userId);
				List<Object> bloodSugar = new ArrayList<Object>();
				List<Object> food = new ArrayList<Object>();
				List<Object> excrcise = new ArrayList<Object>();
				Map<String, Object> mapALLquestion = new HashMap<String, Object>();
				List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
				if (!CollectionUtils.isEmpty(ptcList)) {
					// questiones
					int ipt = 0;
					int isize = ptcList.size();
					Map<String, Object> dataOut = new HashMap<String, Object>();
					Map<String, Object> contVerMap = new HashMap<String, Object>();
					for (ipt = 0; ipt < isize; ipt++) {
						PatientTaskContent ptaskc = ptcList.get(ipt);
						// 获取内容模板
						contVerMap.clear();
						contVerMap.put("templVersionId", ptaskc.getTemplVersionid());
						contVerMap.put("taskId", taskId);
						contVerMap.put("ptSchemeId", psVo.getId());
						contVerMap.put("userId", userId);
						dataOut = getContent(contVerMap);
						// 分类：0：血糖问卷 1：餐谱问卷 2：运动问卷
						int typecode = Integer.parseInt(dataOut.get("typeCode").toString().trim());
						switch (typecode) {
						case 0:
							bloodSugar.add(dataOut.get("contData"));
							break;
						case 1:
							food.add(dataOut.get("contData"));
							break;
						case 2:
							excrcise.add(dataOut.get("contData"));
							break;
						}
						mapALLquestion.put("bloodSugar", bloodSugar);
						mapALLquestion.put("food", food);
						mapALLquestion.put("excrcise", excrcise);

						retOutMap.put("questiones", mapALLquestion);

					}

					// values:上次填写的答案
					HashMap<String, Object> valuesMap = new HashMap<String, Object>();
					HashMap<String, Object> valuesMapOne = new HashMap<String, Object>();
					HashMap<String, Object> valuesMapTow = new HashMap<String, Object>();
					HashMap<String, Object> valuesMapThere = new HashMap<String, Object>();
					HashMap<String, Object> valuesmoning = new HashMap<String, Object>();//早餐
					HashMap<String, Object> valuesAft = new HashMap<String, Object>();//中餐
					HashMap<String, Object> valueseve = new HashMap<String, Object>();//晚餐
					HashMap<String, Object> valuesNight= new HashMap<String, Object>();//加餐
					// List <Map<String,Object>> lists = new
					// ArrayList<Map<String,Object>>();
					HashMap<String, Object> mapInto = new HashMap<String, Object>();
					Map.clear();
					Map.put("taskId", taskId);
					Map.put("contDataTemplType", type);
					Map.put("id", queueId);
					List<FollowQueue> list = queueDao.selectById(Map);
					followDeptId = list.get(0).getDeptId();
					Map.put("queryCondition", "Y");// 需要增加条件
					List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(Map);
					if (!CollectionUtils.isEmpty(ptTaskConList)) {
						int k = 0;
						if (StringUtils.isEmpty(opType)) {
							logger.info("111111111111111111111" + opType);
							for (; k < ptTaskConList.size(); k++) {
								PatientContentData pcdVo = ptTaskConList.get(k);
								valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
							}
							retOutMap.put("values", valuesMap);
						} else {
							for (; k < ptTaskConList.size(); k++) {
								PatientContentData pcdVo = ptTaskConList.get(k);
								if ("0".equals(pcdVo.getOpType())) {
									valuesMapOne.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
								} else if ("1".equals(pcdVo.getOpType())) {
									valuesMapTow.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
									// 分类：0：早 1：中 2：晚 3：加餐
									int typekinds =1000;
									if(!StringUtils.isBlank(pcdVo.getType())) {
										 typekinds = Integer.parseInt(pcdVo.getType());
									}
									switch (typekinds) {
									case 0:
										valuesmoning.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
										break;
									case 1:
										valuesAft.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
										break;
									case 2:
										valueseve.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
										break;
									case 3:
										valuesNight.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
										break;
									}
								} else if("2".equals(pcdVo.getOpType())) {
									valuesMapThere.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
								}
							}
							mapInto.put("bloodSugar", valuesMapOne);
							mapInto.put("food", valuesMapTow);
							mapInto.put("excrcise", valuesMapThere);
							//循环答案和模板信息
							int a = 0;
							int b = 0;
							int lengthFood = food.size();
							int lengthexcrcise = excrcise.size();
							String jsonstr ="";
							net.sf.json.JSONArray matching =null;//匹配后的字符串
				 			for(;a<lengthFood;a++){
								jsonstr = food.get(a).toString();
								net.sf.json.JSONArray node11 = net.sf.json.JSONArray.fromObject(jsonstr);
								net.sf.json.JSONObject node12 = net.sf.json.JSONObject.fromObject(node11.getJSONObject(0));
								if("早餐餐谱".equals(node12.get("label"))) {
									matching = ToolUtils.matching(jsonstr,valuesmoning);
								}else if("午餐餐谱".equals(node12.get("label"))) {
									matching = ToolUtils.matching(jsonstr,valuesAft);
								}else if("晚餐餐谱".equals(node12.get("label"))) {
									matching = ToolUtils.matching(jsonstr,valueseve);
								}else if("加餐餐谱".equals(node12.get("label"))) {
									matching = ToolUtils.matching(jsonstr,valuesNight);
								}else if("".equals(node12.get("label"))) {
									matching = ToolUtils.matching(jsonstr,valuesNight);
								}
								if(matching!=null) {
									food.set(a, matching);
									matching=null;
								}
							}
				 			for(;b<lengthexcrcise;b++){
								jsonstr = excrcise.get(b).toString();
								matching = ToolUtils.matching(jsonstr,valuesMapThere);
								if(matching!=null) {
									excrcise.set(b, matching);
								}
							}

							/*
							 * lists.add(0, valuesMapOne); lists.add(1,
							 * valuesMapTow); lists.add(2, valuesMapThere);
							 */
				 			//重新将修改后的值放入容器中
				 			mapALLquestion.put("food", food);
							mapALLquestion.put("excrcise", excrcise);
							retOutMap.put("questiones", mapALLquestion);

							retOutMap.put("values", mapInto);
						}

					} else {
						retOutMap.put("values", mapInto);
					}
				}

				// task
				Map.clear();
				Map.put("ptTaskId", taskId);
				Map.put("ptTaskName", ptTaskVo.getTaskName());
				Map.put("seqNo", ptTaskVo.getSeqNo());
				Map.put("type", type);
				retOutMap.put("taskInfo", Map);

				// ptQueue
				HashMap<String, Object> oprInfoMap = new HashMap<String, Object>();
				oprInfoMap.put("patientId", ptTaskVo.getUserId());
				oprInfoMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
				oprInfoMap.put("followQueueId", queueId);
				oprInfoMap.put("followDeptId", followDeptId);
				retOutMap.put("ptQueueInfo", oprInfoMap);
				// logger.info("4444444444444444444");
				return retOutMap;
			} else {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "该患者没有加入任何队列！"));
			}
		} else {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "未查询到对应用户信息！"));
		}
	}

	// 用户血糖的增改查
	@Override
	@Transactional
	public Map<String, Object> bloodSugarCommint(Map<String, Object> paramMap) throws Exception {
		logger.info("PatientFollowInit 入参" + paramMap.toString());
		Map<String, Object> Map = new HashMap<String, Object>();
		Map<String, Object> rspMap = new HashMap<String, Object>();
		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		// 通过服务号码和用户姓名查询userid
		String userId = paramMap.get("userId").toString();// 用户id
		String queueId = paramMap.get("queueId").toString();// 队列id
		String schemeId = paramMap.get("ptSchemeId").toString();// 方案id
		String type = paramMap.get("type").toString();// 操作类型
		String taskId = paramMap.get("ptTaskId").toString();
		String typeId = paramMap.get("typeId").toString();
		String struts = paramMap.get("struts").toString();
		String opTime = paramMap.get("opTime").toString();// 操作时间
		//String opType = paramMap.get("typeId").toString();// 操作类型
		Map<String, Object> quesMap = (JSONObject) paramMap.get("questions");

		logger.info("111111111111111111111111111" + paramMap.get("questions").toString());
		QuestionData qd = new QuestionData();
		qd.setContentId("");
		qd.setCreateTime(updateTime);
		qd.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
		qd.setTaskId(taskId);
		qd.setUpdateAccept(updateAccept);
		qd.setUpdateTime(updateTime);
		qd.setUpdateType(Constants.UPDATE_TYPE_INSERT);
		qd.setUserId(userId);
		qd.setPtSchemeid(schemeId);
		qd.setTemplType("1");
		qd.setTypeId(typeId);
		qd.setStruts(struts);
		qd.setQuestions(paramMap.get("questions").toString());
		qd.setOpType("0");
		rspMap.put("queueId", queueId);
		rspMap.put("templType", "8");
		rspMap.put("taskType", "2");
		// 查询通过什么条件查询是否填写了
		Map<String, Object> mapOut = IQuestionsDataDAO.selectQueryCondition(rspMap);
		qd.setQueryCondition(mapOut.get("query_condition").toString());
		if (type.equals(Constants.HANDLE_TYPE_ADD)) {
			// 问卷新增，不管其有没有
			addQuestions(quesMap, qd, opTime, struts, paramMap.get("questions").toString());
		} else if (type.equals(Constants.HANDLE_TYPE_CHANGE)) {
			// 逐条更新
			// logger.info("3333333333333"+quesMap.keySet());
			Iterator<String> iter = quesMap.keySet().iterator();
			while (iter.hasNext()) {
				PatientContentData pcdVo = new PatientContentData();
				String queskey = iter.next();
				String quesvalue = (String) quesMap.get(queskey);

				pcdVo.setContentId("");
				pcdVo.setQuestionAnswer(quesvalue);
				pcdVo.setQuestionId(queskey);
				pcdVo.setTaskId(taskId);
				pcdVo.setUpdateAccept(updateAccept);
				pcdVo.setUpdateTime(updateTime);
				pcdVo.setTemplType("1");
				patientTaskConDao.updatePatientTaskContentDataInfo(pcdVo);

			}
			// 更新用户当前问卷
			List<QuestionData> lists = IQuestionsDataDAO.selectQuestionByTaskid(qd);
			if (lists.size() > 0 && lists != null) {
				String questions = lists.get(0).getQuestions();
				// 将用户当前的问卷修改成传入的值，并入表
				Map<String, Object> mapTojson = ToolUtils.mapTojson(questions);
				Map<String, Object> input = ToolUtils.mapTojson(paramMap.get("questions").toString());
				logger.info(input.toString());
				Iterator<String> iterator = input.keySet().iterator();
				while (iterator.hasNext()) {
					String key = iterator.next();
					mapTojson.put(key, input.get(key));
				}
				// 将map转成json串
				String jsonText = JSON.toJSONString(mapTojson, true);
				qd.setQuestions(jsonText);
				IQuestionsDataDAO.updateQuestionByTaskid(qd);
			} else {
				// 如果查询不到就新增
				addQuestions(quesMap, qd, opTime, struts, paramMap.get("questions").toString());
			}
			// 更新历史轨迹
			/*
			 * HashMap<String, Object> hisConDataMap = new HashMap<String,
			 * Object>(); hisConDataMap.put("taskId", taskId);
			 * hisConDataMap.put("updateAccept", updateAccept);
			 * hisConDataMap.put("updateTime", updateTime);
			 * hisConDataMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
			 * patientTaskConDao.insertContentDataHis(hisConDataMap);
			 */

		} else if (type.equals(Constants.HANDLE_TYPE_DELETE)) {
			// 删除

		}
		return Map;

	}

	// 新增问卷内容公共方法
	public void addQuestions(Map<String, Object> quesMap, QuestionData qd, String opTime, String opType,
			String questions) {
		// 解析建档任务内容（问卷）
		if (null == quesMap || 0 == quesMap.size()) {
			logger.warn("无建档问卷问题--答案记录");
		} else {
			List<PatientContentData> ptcInList = new ArrayList<PatientContentData>();
			Iterator<String> iter = quesMap.keySet().iterator();
			while (iter.hasNext()) {
				PatientContentData pcdVo = new PatientContentData();
				String queskey = iter.next();
				String quesvalue = (String) quesMap.get(queskey);

				pcdVo.setContentId("");
				pcdVo.setCreateTime(qd.getCreateTime());
				pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
				pcdVo.setQuestionAnswer(quesvalue);
				pcdVo.setQuestionId(queskey);
				pcdVo.setTaskId(qd.getTaskId());
				pcdVo.setUpdateAccept(qd.getUpdateAccept());
				pcdVo.setUpdateTime(qd.getUpdateTime());
				pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
				pcdVo.setUserId(qd.getUserId());
				pcdVo.setPtSchemeid(qd.getPtSchemeid());
				pcdVo.setTemplType("1");
				pcdVo.setOpTime(opTime);
				logger.info("opTime****************" + opTime);
				pcdVo.setOpType(opType);
				ptcInList.add(pcdVo);
			}
			// 批量插入
			try {
				patientTaskConDao.savePatientTaskContentDataBatch(ptcInList);
				patientTaskConDao.savePatientTaskContentDataHisBatch(ptcInList);
				List<QuestionData> lists = IQuestionsDataDAO.selectQuestionByTaskid(qd);
				logger.info("IQuestionsDataDAO : " + lists.size());
				if (lists != null && lists.size() > 0) {

					// 将用户当前的问卷修改成传入的值，并入表
					Map<String, Object> mapTojson = ToolUtils.mapTojson(lists.get(0).getQuestions());
					QuestionData pcIn = lists.get(0);
					Map<String, Object> input = ToolUtils.mapTojson(questions);
					logger.info("ceshi: " + input.toString());
					Iterator<String> iterator = input.keySet().iterator();
					while (iterator.hasNext()) {
						String key = iterator.next();
						mapTojson.put(key, input.get(key));
					}
					// 将map转成json串
					String jsonText = JSON.toJSONString(mapTojson, true);
					logger.info("jsonText  : " + jsonText);
					pcIn.setQuestions(jsonText);
					IQuestionsDataDAO.updateQuestionByTaskid(pcIn);

				} else {
					IQuestionsDataDAO.savePatientQuestions(qd);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/***
	 * 1.用户最近6个问卷 2.查询用户删除的模板信息
	 *
	 **/
	@Override
	public List<QuestionData> selectQusetions(Map<String, Object> paramMap) throws Exception {
		logger.info("selectQusetions 入参" + paramMap.toString());
		Map<String, Object> Map = new HashMap<String, Object>();
		// 通过服务号码和用户姓名查询userid
		String userId = paramMap.get("userId").toString();// 用户id
		String schemeId = paramMap.get("schemeId").toString();// 方案id
		String taskId = paramMap.get("taskId").toString();
		String typeId = paramMap.get("typeId").toString();
		String struts = paramMap.get("struts").toString();
		int code = Integer.parseInt(paramMap.get("code").toString());
		String opType = (String) paramMap.get("opType");
		Map.put("taskId", taskId);
		Map.put("typeId", typeId);
		Map.put("userId", userId);
		Map.put("struts", struts);
		Map.put("schemeId", schemeId);
		Map.put("code", code);
		Map.put("opType", opType);
		// 通过服务号码和用户姓名查询userid
		List<QuestionData> lists = null;
		// logger.info("opType*********"+opType);
		if (opType == null || "".equals(opType) || "null".equals(opType)) {
			lists = IQuestionsDataDAO.selectQuestionSixTime(Map);
		} else {
			lists = IQuestionsDataDAO.selectQuestionDelete(Map);
		}

		return lists;
	}

	// 运动量修改针对当前用户进行修改
	@Override
	@Transactional
	public Map<String, Object> changeExercise(Map<String, Object> paramMap) throws Exception {
		logger.info("selectQusetions 入参" + paramMap.toString());
		HashMap<String, Object> Map = new HashMap<String, Object>();
		// 通过服务号码和用户姓名查询userid
		String userId = paramMap.get("userId").toString();// 用户id
		String schemeId = paramMap.get("schemeId").toString();// 方案id
		String taskId = paramMap.get("taskId").toString();
		String oldId = (String) paramMap.get("oldId");
		String typeId = paramMap.get("typeId").toString();
		String struts = paramMap.get("struts").toString();
		String code = paramMap.get("code").toString(); // 操作类型
		String questions = paramMap.get("questions").toString();
		String typeName = paramMap.get("typeName").toString();
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		PtContent pc = new PtContent();
		Map.put("code", code);
		Map.put("questions", questions);
		pc.setTaskId(taskId);
		pc.setUserId(userId);
		pc.setTemplData(questions);
		pc.setPtSchemeid(schemeId);
		Map.put("taskId", taskId);
		Map.put("userId", userId);
		Map.put("ptSchemeId", schemeId);
		// c查询当前用户下所有的问卷模板
		List<PtContent> lists = IPtContentDAO.selectPtContentByUserId(Map);
		// 循环匹配现在用户需要修改的问卷模板
		for (int i = 0; i < lists.size(); i++) {
			PtContent pcone = new PtContent();
			pcone = lists.get(i);
			String TemplData = pcone.getTemplData();
			JSONArray node11 = JSONArray.parseArray(TemplData);
			JSONObject node12 = (JSONObject) node11.get(0);
			logger.info("aaaaaaaaaaaaaa" + node12.get("label"));
			if (node12.get("label").equals(typeName)) {
				Map.put("TemplData", node11.toString());
				String str = ToolUtils.changeJson(Map);// 处理问卷json串
				pcone.setUpdateAccept(updateAccept);
				pcone.setUpdateTime(updateTime);
				// 先入历史表
				pcone.setUpdateType(Constants.UPDATE_TYPE_UPDATE_U);
				pcone.setTemplData(str);
				IPtContentHisDAO.savePatientHisContent(pcone);
				// 更新当期那患者的问卷模板
				IPtContentDAO.updatePtContentByUserId(pcone);
			}
		}

		// 判断是否需要删除pt_questiondata_info中的数据
		if (!StringUtils.isBlank(oldId) && !"NULL".equals(oldId) && !"null".equals(oldId)) {
			logger.info("oldId!!!!!!!!!!!!!" + oldId);
			Map<String, Object> mapIn = new HashMap<String, Object>();
			mapIn.put("oldId", oldId);
			mapIn.put("opType", Constants.UPDATE_TYPE_DELETE);
			IQuestionsDataDAO.deleteQuestionDelete(mapIn);
		}

		if (code.equals(Constants.HANDLE_TYPE_DELETE) && !struts.equals("0")) {
			QuestionData qd = new QuestionData();
			qd.setContentId("");
			qd.setCreateTime(updateTime);
			qd.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
			qd.setTaskId(taskId);
			qd.setUpdateAccept(updateAccept);
			qd.setUpdateTime(updateTime);
			qd.setUpdateType(Constants.UPDATE_TYPE_INSERT);
			qd.setUserId(userId);
			qd.setPtSchemeid(schemeId);
			qd.setTemplType("1");
			qd.setTypeId(typeId);
			qd.setStruts(struts);
			qd.setQuestions(questions);
			qd.setOpType("D");
			IQuestionsDataDAO.savePatientQuestions(qd);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		return map;
	}

	// 获取模板内容私有接口实现
	public Map<String, Object> getContent(Map<String, Object> paramIn) throws Exception {
		Map<String, Object> outMap = new HashMap<String, Object>();
		HashMap<String, Object> contVerMap = new HashMap<String, Object>();
		// logger.info("*******"+paramIn.toString());
		// 后续从redis缓存获取，这里先从物理库中获取
		boolean flag = false;
		contVerMap.put("id", paramIn.get("templVersionId"));
		contVerMap.put("taskId", paramIn.get("taskId"));
		contVerMap.put("userId", paramIn.get("userId"));
		contVerMap.put("ptSchemeId", paramIn.get("ptSchemeId"));
		List<PtContent> ctvListone = IPtContentDAO.selectPtContentByUserId(contVerMap);
		String templDataStr = "";
		String typeCode = "";
		if (!ctvListone.isEmpty()) {
			PtContent ctvone = ctvListone.get(0);
			templDataStr = ctvone.getTemplData();
			typeCode = ctvone.getTypeCode();
			flag = true;
		}
		// logger.info("templDataStr###########" + templDataStr);
		if (StringUtils.isBlank(templDataStr) && !flag) {
			// throw new
			// AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_IS_NULL,
			// "任务内容模板值为空！");
			List<ContentTemplVersion> ctvList = contentTemplDao.selectContentTemplById(contVerMap);
			// logger.info("111111111111" + ctvList.toString());
			if (null == ctvList || 0 == ctvList.size()) {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPL_NOT_EXIST, "未查询到任务内容模板记录！");
			}
			ContentTemplVersion ctv = ctvList.get(0);

			templDataStr = ctv.getTemplData();
			typeCode = ctv.getTypeCode();
			if (StringUtils.isBlank(templDataStr)) {
				return outMap;
			}

		}

		// 数据库默认配置为json数组格式
		JSONArray templJsonArray = null;
		try {
			templJsonArray = JSON.parseArray(templDataStr);
			outMap.put("contData", templJsonArray);
			outMap.put("typeCode", typeCode);
		} catch (JSONException arex) {
			logger.error("任务内容模板格式配置错误，非json数组格式： " + arex.getMessage());

			// 非json数组格式，则按json格式再解析
			JSONObject templJsonObject = null;
			try {
				templJsonObject = JSON.parseObject(templDataStr);
				outMap.put("contData", templJsonObject);
			} catch (JSONException exobj) {
				exobj.printStackTrace();
				// 后续重写异常类
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_CONFIG_IRREGULAR,
						"问卷模板配置错误，非json格式！"));
			}
		} catch (AppException appex) {
			throw (appex);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUES_TEMPLDATA_CONFIG_IRREGULAR,
					"问卷模板格式解析错误：" + ex.getMessage());
		}

		return outMap;
	}

	// 实例化模板
	@Transactional
	public void addPtcontents(Map<String, Object> paramMap) throws Exception {
		HashMap<String, Object> argMap = new HashMap<String, Object>(paramMap);
		HashMap<String, Object> retOut = new HashMap<String, Object>();
		List<HashMap<String, Object>> retList = new ArrayList<HashMap<String, Object>>();
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		List<Map<String, Object>> conTemplList = patientTaskDao.selectContentTemplByPtSchemeId(argMap);
		if (!CollectionUtils.isEmpty(conTemplList)) {
			HashMap<String, Object> templMap = new HashMap<String, Object>();
			String conTemplStr = "";
			int it = 0;
			int size = conTemplList.size();

			Map<String, Object> equalMap = new HashMap<String, Object>();
			Map<String, Object> conMap = new HashMap<String, Object>();
			// 找出模板内容相同的问卷
			for (it = 0; it < size; it++) {
				conMap = conTemplList.get(it);
				String templType = (String) conMap.get("templType");
				String templVersionId = (String) conMap.get("templVersionid");
				if (Constants.QUESTIONNAIRE_TYPE_0.equals(templType)) {
					templMap.put("id", templVersionId);
					List<ContentTemplVersion> ctvList = contentTemplDao.selectContentTemplNoTextById(templMap);
					if (null == ctvList || 0 == ctvList.size()) {
						continue;
					}
					String equalId = ctvList.get(0).getEqualId();
					if (!StringUtils.isEmpty(equalId)) {
						equalMap.put(equalId, templVersionId);
					}
				}
			}
			logger.warn("equalMap==" + equalMap.toString());

			for (it = 0; it < size; it++) {
				HashMap<String, Object> quesMap = new HashMap<String, Object>();
				conMap = conTemplList.get(it);
				conTemplStr = (String) conMap.get("templVersionid");
				String templType = (String) conMap.get("templType");
				if (!Constants.QUESTIONNAIRE_TYPE_0.equals(templType)) {
					if (null != equalMap.get(conTemplStr)) {
						// 该问卷与门诊问卷内容相同，需要剔除
						logger.warn("erase templVersionId==" + conTemplStr);
						continue;
					}
				}
				// 此处后续需要使用redis缓存
				templMap.put("id", conTemplStr);
				List<ContentTemplVersion> ctvList = contentTemplDao.selectContentTemplById(templMap);
				if (null == ctvList || 0 == ctvList.size()) {
					continue;
				}
				ContentTemplVersion ctVo = ctvList.get(0);
				quesMap.put("id", ctVo.getId());
				quesMap.put("templId", ctVo.getTemplId());
				quesMap.put("templVersion", ctVo.getTemplVersion() + "");
				quesMap.put("templData", ctVo.getTemplData());
				quesMap.put("createTime", currTime);
				quesMap.put("updateTime", currTime);
				quesMap.put("typeCode", ctVo.getTypeCode());
				quesMap.put("remark", "线上问卷");
				quesMap.put("equalId", ctVo.getEqualId());
				quesMap.put("taskId", conMap.get("taskId").toString());
				quesMap.put("ptSchemeid", argMap.get("ptSchemeId").toString());
				quesMap.put("queueId", argMap.get("queueId").toString());
				quesMap.put("userId", argMap.get("userId").toString());
				retList.add(quesMap);
			}
			// 批量插入
			IPtContentDAO.savePatientContentBatch(retList);
		}
		retOut.put("total", retList.size());
		retOut.put("rows", retList);

	}

	/**
	 * 查询运动消耗和食物蕴含的能量
	 *
	 **/
	@Override
	public List<Map<String, Object>> selectEnegry(Map<String, Object> paramMap) throws Exception {
		logger.info("selectQusetions 入参" + paramMap.toString());
		List<Map<String, Object>> lists = IBsEnegryInfoDAO.selectEnegry(paramMap);
		return lists;
	}

	/**
	 * 食物和运动完成情况提交服务 20170713 wuyz
	 */
	@Override
	@Transactional
	public Map<String, Object> doSubfoodAndExcierse(Map<String, Object> inMap) throws Exception {

		logger.info("inMap~~~~~~" + inMap);
		Map<String, Object> map = new HashMap<String, Object>();
		String updateTime = (String) inMap.get("updateTime");
		String updateAccept = (String) inMap.get("updateAccept");
		String ptSchemeid = (String) inMap.get("ptSchemeid");
		String taskId = (String) inMap.get("taskId");
		String userId = (String) inMap.get("userId");
		String opType = (String) inMap.get("opType");
		String struts =  (String) inMap.get("struts");
		String type =  (String) inMap.get("type");
		// 获取当前时间
		String opTime = DateUtil.getCurrDate();
		Map<String, Object> quesMap = (JSONObject) inMap.get("contentData");
		List<PatientContentData> ptcInList = new ArrayList<PatientContentData>();
		Iterator<String> iter = quesMap.keySet().iterator();
		while (iter.hasNext()) {

			PatientContentData pcdVo = new PatientContentData();
			String queskey = iter.next();
			String quesvalue = (String) quesMap.get(queskey);

			pcdVo.setContentId("");
			pcdVo.setCreateTime(updateTime);
			pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
			pcdVo.setQuestionAnswer(quesvalue);
			pcdVo.setQuestionId(queskey);
			pcdVo.setTaskId(taskId);
			pcdVo.setUpdateAccept(updateAccept);
			pcdVo.setUpdateTime(updateTime);
			pcdVo.setOpTime(opTime);
			pcdVo.setType(type);
			if (opType.equals(Constants.UPDATE_TYPE_INSERT)) {
				pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
			} else if (opType.equals(Constants.UPDATE_TYPE_DELETE)) {
				pcdVo.setUpdateType(Constants.UPDATE_TYPE_DELETE);
			}
			pcdVo.setUserId(userId);
			pcdVo.setPtSchemeid(ptSchemeid);
			// 非门诊问卷，后续补充
			pcdVo.setTemplType("1");
			pcdVo.setOpType(struts);
			ptcInList.add(pcdVo);
		}

		if (opType.equals(Constants.UPDATE_TYPE_INSERT)) {
			// 批量插入
			patientTaskConDao.savePatientTaskContentDataBatch(ptcInList);
			patientTaskConDao.savePatientTaskContentDataHisBatch(ptcInList);
		} else if (opType.equals(Constants.UPDATE_TYPE_DELETE)) {

			PatientContentData pcdVo = new PatientContentData();
			pcdVo = ptcInList.get(0);
			// 先入历史
			patientTaskConDao.savePatientTaskContentDataHisBatch(ptcInList);
			// 更新任务内容详情
			logger.info(pcdVo.getTaskId());
			logger.info(pcdVo.getOpTime());
			logger.info(pcdVo.getUserId());
			logger.info(pcdVo.getQuestionId());

			patientTaskConDao.deletePtContentDataInfoByConDt(pcdVo);
		}

		return map;
	}

	/**
	 * 查询当前用户的实时模板信息 20170714 wuyz
	 */
	@Override
	public Map<String, Object> queryCurrentTmplet(HashMap<String, Object> paramMap) throws Exception {
		logger.info("selectQusetions 入参" + paramMap.toString());
		HashMap<String, Object> Map = new HashMap<String, Object>();
		// 通过服务号码和用户姓名查询userid
		String userId = paramMap.get("userId").toString();// 用户id
		String schemeId = paramMap.get("schemeId").toString();// 方案id
		String taskId = paramMap.get("taskId").toString();
		String typeName = paramMap.get("typeName").toString();
		Map.put("taskId", taskId);
		Map.put("userId", userId);
		Map.put("ptSchemeId", schemeId);
		// c查询当前用户下所有的问卷模板
		List<PtContent> lists = IPtContentDAO.selectPtContentByUserId(Map);
		// 循环匹配现在用户需要修改的问卷模板
		for (int i = 0; i < lists.size(); i++) {
			PtContent pcone = new PtContent();
			pcone = lists.get(i);
			String TemplData = pcone.getTemplData();
			JSONArray node11 = JSONArray.parseArray(TemplData);
			JSONObject node12 = (JSONObject) node11.get(0);
			logger.info("aaaaaaaaaaaaaa" + node12.get("label"));
			if (node12.get("label").equals(typeName)) {
				Map.put("TemplData", node11.toString());
			}
		}
		return Map;
	}

}
